/**
  * a socket-based time of day server
  */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <strings.h>

#define PORTNUM 13000	/* time service phone number */
#define HOSTLEN 256
#define oops(msg) {perror(msg); exit(1);}

int main(int ac, char *av[]) {
	struct sockaddr_in saddr;					// build our address here
	struct hostent *hp;							// this is part of out addresses
	char hostname[HOSTLEN];						
	int sock_id, sock_fd;						// line id, file desc

	FILE *sock_fp;								// use socket as a stream
	char *ctime();								// convert secs to string
	time_t thetime;								// the time we report

	// step1: ask kernel for a socket
	sock_id = socket(PF_INET, SOCK_STREAM, 0);	// get a socket
	if (sock_id == -1) {
		oops("socket");
	}

	// step2: bind address to socket. Address is host, port
	bzero((void *)&saddr, sizeof(saddr));		// clear out struct
	
	gethostname(hostname, HOSTLEN);
	hp = gethostbyname(hostname);				// get info about host

	printf("hostname = %s", hostname);

//	bcopy((void *)hp->h_addr, (void *)&saddr.sin_addr, hp->h_length);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	saddr.sin_port = htons(PORTNUM);			// fill in socket port
	saddr.sin_family = AF_INET;					// fill in addr family

	printf("sin_port = %d", saddr.sin_port);
	printf("-----test-up-----\n");
	if (bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) != 0) {
		oops("bind");
	}
	printf("-----test------\n");


	// step3: allow incoming calls with Qsize = 1 on socket
	if (listen(sock_id, 1) != 0) {
		oops("listen");
	}


	// main loop, accept(), write(), close()
	while (1) {
		sock_fd = accept(sock_id, NULL, NULL);		// wait for call
		printf("Wow! got a call! \n");
		if (sock_fd == -1) {
			oops("accept");
		}

		sock_fp = fdopen(sock_fd, "w");				// write to the socket as a stream
		if (sock_fp == NULL) {
			oops("fdopen");
		}

		thetime = time(NULL);

		fprintf(sock_fp, "The time here is..");
		fprintf(sock_fp, "%s", ctime(&thetime));
		fclose(sock_fp);							// release connection
	}

}
